<?php
!defined('QAPP') AND exit('Forbidden');
//dumpForInstall(session_get('site_db'));

if (file_exists(AppDir . 'apphash.php') || file_exists("../config.php")) {
    session_clear();
    header("location:?step=10");
    exit();
}
function install()
{

    $dbConfig = array(
        'type' => '',
        'sqlite' => array(
            'file' => 'auto'
        ),
        'mysql' => array(
            'host' => '127.0.0.1',
            'port' => '3306',
            'user' => '',
            'password' => '',
            'dbname' => ''
        ),
        'tableEx' => ""
    );


    if (session_get('site_db')) {
        $site_db_40 = session_get('site_db');
//        dumpForInstall($site_db_40);
        $dbConfig['type'] = $site_db_40['database'];
        $dbConfig['tableEx'] = isset($site_db_40['pre']) ? $site_db_40['pre'] : '';

        if ($dbConfig['tableEx']) {
            if (substr($dbConfig['tableEx'], -1, 1) != "_") {
                $dbConfig['tableEx'] .= "_";
            }
        }
        if ($dbConfig['type'] == "mysqlpdo") {
            $dbConfig['mysql']['host'] = $site_db_40['host'];
            $dbConfig['mysql']['port'] = isset($site_db_40['port']) ? $site_db_40['port'] : "3306";
            $dbConfig['mysql']['user'] = $site_db_40['user'];
            $dbConfig['mysql']['password'] = $site_db_40['password'];
            $dbConfig['mysql']['dbname'] = $site_db_40['dbname'];
        } else {
            //sqlite不需要前缀
            $dbConfig['tableEx'] = "";
        }
    } else {
        session_set('step', 40);
        header("location:?step=40&errmsg=无法获取数据库配置，请重新提交");
        exit();
    }

    $sitehash = getCuidForInstall();
    $dbhash = getCuidForInstall();

    $site_db = array();

    $config = file_get_contents("config-default.php");
    $config = str_replace("@tablepre", $dbConfig['tableEx'], $config);
    $config = str_replace("@dbtype", $dbConfig['type'], $config);

    $db = new QAppDB();
    if ($dbConfig['type'] == "sqlite" || $dbConfig['type'] == "sqlitepdo") {
        $dbfile = AppDir . 'data/' . $dbhash . '.db';
        $dbConfig['sqlite']['file'] = $dbfile;
        $site_db = array('database' => 'sqlitepdo', 'dbfile' => $dbfile);
        $ret = $db->connect($site_db);
        if ($ret !== true) {
            return $ret;
        }
    } else if ($dbConfig['type'] == "mysql" || $dbConfig['type'] == "mysqlpdo") {
        //如果mysql不存在此数据库，不带dbname，才能连接
        $site_db = array('database' => 'mysqlpdo', 'host' => $dbConfig['mysql']['host'], 'user' => $dbConfig['mysql']['user'], 'password' => $dbConfig['mysql']['password']);
        $ret = $db->connect($site_db);
        if ($ret !== true) {
            return $ret;
        }

        $createok = $db->creatMysqlDatabase($dbConfig['mysql']['dbname']);
        if (!$createok) {
            return "MySQL数据库创建库失败，如果您的账户没有创建数据库的权限，请手动创建<code>{$dbConfig['mysql']['dbname']}</code>数据库后进行重试";
        }

        $config = str_replace("@mysqlhost", $dbConfig['mysql']['host'], $config);
        $config = str_replace("@mysqlport", $dbConfig['mysql']['port'], $config);
        $config = str_replace("@mysqluser", $dbConfig['mysql']['user'], $config);
        $config = str_replace("@mysqlpassword", $dbConfig['mysql']['password'], $config);
        $config = str_replace("@mysqldbname", $dbConfig['mysql']['dbname'], $config);
    }

    //定义表前缀
    define('TableEx', $dbConfig['tableEx']);
    //导入结构和数据
    $jsonfile = file_get_contents(CoreDir . 'data/ddl.json');
    $json = json_decode($jsonfile, 1);

    foreach ($json as $table => $columes) {
        if ($table == 'channel') {
            $db->creatTable($dbConfig['tableEx'] . $table, 'cid');
        } else {
            $db->creatTable($dbConfig['tableEx'] . $table);
        }
        foreach ($columes as $colume) {
            $db->addColumn($dbConfig['tableEx'] . $table, $colume['name'], $colume['type']);
        }
    }

    $db->restore_data_from_json($dbConfig['tableEx'], CoreDir . 'data/data.json');

    $apphash_ok = file_put_contents(AppDir . 'apphash.php', "<?php define('SiteHash','{$sitehash}');define('DBHash','{$dbhash}');");
    $config_ok = file_put_contents("../config.php", $config);

    if ($apphash_ok && $config_ok) {
        session_clear();
        return true;
    } else {
        if ($apphash_ok) {
            unlink(AppDir . 'apphash.php');
        }

        if ($config_ok) {
            unlink("../config.php");
        }

        @unlink(AppDir . "data/{$dbhash}.sql");
        return '<code>public/config.php</code>配置文件创建失败';
    }
}

$install_ret = install();
if ($install_ret === true) {
    ?>
    <h2 style='text-align: center'>恭喜您，已安装成功</h2>
    <p style='text-align: center;color: #ff0054'>在正式运营前，记得删除<code>public/install</code>目录哦</p>

    <div class="panel panel-default">
        <div class="panel-body">
            <a class="btn btn-default" href="../" target="_blank">前往前台</a>
            <a class="btn btn-default" href="../admin" target="_blank">登录后台</a>
        </div>
    </div>

    <div class="panel panel-default">
        <div class="panel-body">
            <p>后台帐号信息</p>
            <p>开发者帐号：<code>superadmin</code></p>
            <p>开发者密码：<code>123456</code></p>
            <hr>
            <p>管理员帐号：<code>admin</code></p>
            <p>管理员密码：<code>123456</code></p>
        </div>
    </div>


    <?php
} else {
    echo "<p class='text-center'>$install_ret</p>";
    echo "<p class='text-center'><a href='?step=40'>返回上一步</a></p>";
    echo "<p class='text-center'><a href='?step=50'>刷新</a></p>";
}